﻿

using System;
using System.Collections.Generic;
using System.Data;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

using Gift.DAL;
using Gift.Model;


    public partial class admin_order_MeterialOrderAdd : BaseAdmin
    {
        readonly OrderAccount theOrderAccount = new OrderAccount();
        readonly DALCardType theCardType = new DALCardType();
        readonly Card theCard = new Card();
        readonly dalCar theDalCar = new dalCar();
        readonly Car theCar = new Car();
        List<tbProfessionAreaType> lstProfessionType = new List<tbProfessionAreaType>();
        readonly DALProfessionAreaType theProfessionAreaType = new DALProfessionAreaType();
        readonly MemberAccount theMemberAccount = new MemberAccount();
        readonly Order theOrder = new Order();

        public string address = "";
        public string carid = "0";
        public string carinfo = "";
        public string cname = "";
        public string email = "";
        public string istrue = "0";
        public string phone = "";
        public string post = "";
        public string score1 = "0";
        public string score2 = "0";
        public string score3 = "0";
        public string shipmsg = "";
        public string tel = "";
        public string totalprice = "0";
        public string totalscore = "0";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.BindNoComplateOrder();
                this.txtSendDate.Text = DateTime.Now.AddDays(2).ToString("yyyy-MM-dd");
                this.txtNum.Text = "1";
                this.ddlProductList.Items.Add(new ListItem("没有供您选择的商品!"));
                BindProfessionAreaType();
            }
           
        }

        void BindNoComplateOrder()
        {
            DataSet ds;
            ds = theOrderAccount.GetNoComplateAccountList();
            if (ds != null && ds.Tables.Count > 0)
            {
                this.ddlNoComplateOrder.DataTextField = "OrderCode";
                this.ddlNoComplateOrder.DataValueField = "OrderCode";
                this.ddlNoComplateOrder.DataSource = ds.Tables[0].DefaultView;
                this.ddlNoComplateOrder.DataBind();
                this.ddlNoComplateOrder.Items.Insert(0, new ListItem("选择未完成订单编号...", ""));
            }
        }


        void GenerateOrderCode()
        {
            if (!string.IsNullOrEmpty(Request.QueryString["orderCode"]))
            {
                this.lblOrderCode.Text = Request.QueryString["orderCode"];
                this.BindProfessionAreaType();
            }
            else
            {
                this.lblOrderCode.Text = theOrderAccount.GenerateOrderCode();
            }
        }


        void BindProfessionAreaType()
        {
            tbProfessionAreaType oProfessionAreaType = new tbProfessionAreaType();
             DataSet ds = theProfessionAreaType.GetList("1=1");
             this.ddlProfessional.DataTextField = "Name";
             this.ddlProfessional.DataValueField = "Id";
             this.ddlProfessional.DataSource = ds;
             this.ddlProfessional.DataBind();
        }

      
        void BindProductList()
        {
            if (!string.IsNullOrEmpty(this.lblOrderCode.Text.Trim()))
            {
                DataTable dtResult = theCar.GetListByOrderCode(this.lblOrderCode.Text.Trim());
                this.GridView1.DataSource = dtResult.DefaultView;
                this.GridView1.DataBind();
            }
        
        }


        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string sContents = "";// 暂未添加
            if (e.CommandName == "edi")
            {
                if (ViewState["editRowIndex"] != null)
                {
                    int iRowIndex = int.Parse(ViewState["editRowIndex"].ToString());
                    LinkButton lbtEdit = GridView1.Rows[iRowIndex].FindControl("lbtEdit") as LinkButton;
                    LinkButton lbtSave = GridView1.Rows[iRowIndex].FindControl("lbtSave") as LinkButton;
                    LinkButton lbtCancel = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("lbtCancel") as LinkButton;
                    TextBox txtNum = GridView1.Rows[iRowIndex].FindControl("txtNum") as TextBox;
                    lbtEdit.Visible = true;
                    lbtSave.Visible = false;
                    lbtCancel.Visible = false;
                    txtNum.Text = ViewState["num"].ToString();
                    txtNum.Enabled = false; ;
                }
                LinkButton lbtEdit2 = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("lbtEdit") as LinkButton;
                LinkButton lbtSave2 = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("lbtSave") as LinkButton;
                LinkButton lbtCancel2 = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("lbtCancel") as LinkButton;
                TextBox txtNum2 = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("txtNum") as TextBox;
                lbtEdit2.Visible = false;
                lbtSave2.Visible = true;
                lbtCancel2.Visible = true;
                txtNum2.Enabled = true;
                ViewState["editRowIndex"] = e.CommandArgument.ToString();
                ViewState["num"] = txtNum2.Text;
            }
            else if (e.CommandName == "sav")
            {
                LinkButton lbtEdit3 = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("lbtEdit") as LinkButton;
                LinkButton lbtSave3 = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("lbtSave") as LinkButton;
                LinkButton lbtCance3 = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("lbtCancel") as LinkButton;
                TextBox txtNum3 = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("txtNum") as TextBox;
                 Label lblPrice3 = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("lblPrice") as Label;
                 Label lblProfessionTypeId = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("lblProfessionTypeId") as Label; 
                int iProductId =  int.Parse(((HyperLink)GridView1.Rows[int.Parse(e.CommandArgument.ToString())].Cells[0].Controls[0]).Text);
                if (txtNum3.Text.Trim() == "0")
                {
                    theCar.Delete(this.lblOrderCode.Text.Trim(), iProductId,sContents);
                }
                else
                {
                    decimal dRemanants = 0;
                    if (ViewState["amount"] != null)
                    {
                        Hashtable htAmount = ViewState["amount"] as Hashtable;
                        decimal dSumPriceByProdId = theCar.GetSumPriceByProdId(int.Parse(((HyperLink)GridView1.Rows[int.Parse(e.CommandArgument.ToString())].Cells[0].Controls[0]).Text),int.Parse(lblProfessionTypeId.Text),sContents);
                        dRemanants = decimal.Parse(htAmount[int.Parse(lblProfessionTypeId.Text)].ToString()) - int.Parse(txtNum3.Text) * decimal.Parse(lblPrice3.Text) - dSumPriceByProdId;

                        if (dRemanants < 0)
                        {
                            Response.Write("<script>alert('余额不够！');</script>");
                            return;
                        }
                        else
                        {
                            tbCar oCar = new tbCar();
                            oCar.OrderCode = this.lblOrderCode.Text.Trim();
                            oCar.ProdNumber = int.Parse(txtNum3.Text);
                            oCar.ProdPrice = decimal.Parse(lblPrice3.Text);
                            oCar.ProductId = iProductId;
                            theCar.Update(oCar);
                        }
                    }
                }

                lbtEdit3.Visible = true;
                lbtSave3.Visible = false;
                lbtCance3.Visible = false;
                txtNum3.Enabled = false; ;
                Response.Write("<script>alert('保存成功！'); </script>");
                this.BindProductList();
                this.BindProfessionAreaType();
               
            }
            else if (e.CommandName == "can")
            {
                LinkButton lbtEdit4 = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("lbtEdit") as LinkButton;
                LinkButton lbtSave4 = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("lbtSave") as LinkButton;
                LinkButton lbtCancel4 = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("lbtCancel") as LinkButton;
                TextBox txtNum4 = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("txtNum") as TextBox;
                lbtEdit4.Visible = true;
                lbtSave4.Visible = false;
                lbtCancel4.Visible = false;
                txtNum4.Enabled = false;
            }
            else if (e.CommandName == "del")
            {
                int iProductId = int.Parse(((HyperLink)GridView1.Rows[int.Parse(e.CommandArgument.ToString())].Cells[0].Controls[0]).Text);
                theCar.Delete(this.lblOrderCode.Text.Trim(), iProductId, sContents);
                Response.Write("<script>alert('删除成功！'); </script>");
                this.BindProductList();
                this.BindProfessionAreaType();
            }
            if (ViewState["professionAreaSelectID"] != null)
            {
               // this.rbtlProfessionList.Items.FindByValue(ViewState["professionAreaSelectID"].ToString()).Selected = true;
            }
        }

        protected void ibtnSubmit_Click(object sender, ImageClickEventArgs e)
        {
            if (this.lblOrderCode.Text == "")
            {
                base.Response.Write("<script  language='javascript'>alert('请选择添加新订单或者选择未完成的订单!');</script>");
                return;
            }
            dbOrder oOrder = new dbOrder();
            dbCar odbCar = new dbCar();
            tbCar oCar = new tbCar();
            decimal dTotalPrice = theCar.GetSpendTotalPrice(this.lblOrderCode.Text.Trim());



            long uOrderId = DateTime.Now.Ticks;
            oOrder.orderid = uOrderId;
            oOrder.ordercode = this.lblOrderCode.Text.Trim();
            oOrder.pay = 16;//付款方式为实物
            oOrder.states = 0;
            oOrder.cname = base.AdminUser;
            oOrder.cname1 = this.txtUserName.Text.Trim();
            oOrder.tel1 = this.txtTel.Text.Trim();
            oOrder.phone1 = this.txtPhone.Text.Trim();
            oOrder.post1 = this.txtPost.Text.Trim();
           // oOrder.address1 = this.AddressArea1.GetProvenceArea() + this.txtAddress.Text.Trim();
            oOrder.Senddate = this.txtSendDate.Text.Trim() == "" ? DateTime.Now.AddDays(2) : DateTime.Parse(this.txtSendDate.Text.Trim()); 
            oOrder.ordertime = DateTime.Now;
            oOrder.languages = 1;

            oOrder.totalprice =dTotalPrice.ToString();
            oOrder.content = this.txtRemark.Text.ToString();
            theOrder.Add(oOrder);

            theDalCar.AddTempToReal(this.lblOrderCode.Text.Trim(),oOrder.orderid);
            theOrderAccount.UpdateComplateAccount(this.lblOrderCode.Text.Trim());
            base.Response.Write("<script  language='javascript'>alert('提交订单成功!请记住订单编号(" + oOrder.ordercode + ")以便查询!');window.location.href='order.aspx'</script>");

        }



        protected void ddlNoComplateOrder_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.ddlNoComplateOrder.SelectedItem.Value))
            {

                this.txtAddress.Text = "";
                this.txtSendDate.Text = DateTime.Now.AddDays(2).ToString("yyyy-MM-dd");
                this.txtPhone.Text = "";
                this.txtPost.Text = "";
                this.txtTel.Text = "";
                this.txtUserName.Text = "";
                this.lblOrderCode.Text = this.ddlNoComplateOrder.SelectedItem.Value;
                this.BindProductList();
                this.BindProfessionAreaType();     
            }
        }



        protected void ibtnAddProdut_Click(object sender, ImageClickEventArgs e)
        {
            if (this.ddlProfessional.SelectedItem == null)
            {
                base.Response.Write("<script  language='javascript'>alert('请选择专区类别!');</script>");
                return;
            }
            else if (this.ddlProductList.SelectedItem.Value == "0")
            {
                base.Response.Write("<script  language='javascript'>alert('请添加要兑换的商品!');</script>");
                return;
            }
            try
            {
                int.Parse(this.txtNum.Text);
            }catch
            {
                  base.Response.Write("<script  language='javascript'>alert('数量必须为整数!');</script>");
                return;
            }
           
              Hashtable htAmount = (Hashtable)ViewState["amount"];
              String[] ids = this.ddlProductList.SelectedItem.Value.Split(',');
             

                    try
                    {
                        //添加数据
                        tbCar oCar = new tbCar();
                        oCar.OrderCode = this.lblOrderCode.Text.Trim();
                        oCar.ProdNumber = int.Parse(txtNum.Text);
                        oCar.ProdPrice = decimal.Parse(ids[1]);
                        oCar.ProductId = int.Parse(ids[0]);
                        oCar.UpdateDate = DateTime.Now;
                        theCar.Add(oCar);
                        base.Response.Write("<script  language='javascript'>alert('添加成功！');</script>");
                        this.BindProductList();
                        this.BindProfessionAreaType();
                    }
                    catch
                    {
                        Response.Redirect("OrderAdd.aspx");
                    }
              
        }
   

        protected void ibtnNewOrder_Click(object sender, ImageClickEventArgs e)
        {
            this.GenerateOrderCode();
            this.BindProductList();
            this.BindProfessionAreaType();
        }

        protected void ddlProfessional_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.ddlProductList.Items.Clear();
            DataTable table = SQLAccess.GreatDs("select convert(varchar(10),proid) + ', ' + convert(varchar(10),saleprice) as id ,proname + '('+convert(varchar(10),saleprice)+')' as name ,saleprice,prosmallpic  from DB_Shoppro where proisprofession=1 and isnull(proku,0)>0  and ProfessionAreaTypeId= " + this.ddlProfessional.SelectedItem.Value + " order by proname").Tables[0];
            this.ddlProductList.DataTextField = "name";
            this.ddlProductList.DataValueField = "id";
            this.ddlProductList.DataSource = table.DefaultView;
            this.ddlProductList.DataBind();

            if (this.ddlProductList.Items.Count <= 0)
            {
                this.ddlProductList.Items.Add(new ListItem("没有供您选择的商品!", "0"));
            }
        }




    }
